package ws

import (
	"kugo/event"
	"kugo/utils"
	"reflect"
)

type pack struct {
	Cmd    string `json:"cmd,omitempty"`
	Data   string `json:"data,omitempty"`
	Status int64  `json:"status"`
}

func analyzeCmd(data string) (pack, error) {
	var result pack
	err := utils.StringToStruct(data, &result)
	return result, err
}

func buildPack(cmd string, data interface{}) string {
	var result string
	var p = &pack{}
	p.Cmd = cmd
	p.Data = utils.Struct2JSON(data)

	value := reflect.ValueOf(data)
	valueType := value.Type()
	if valueType.Kind() == reflect.String {
		p.Status = 1
	} else {
		p.Status = 0
	}
	result = utils.Struct2JSON(p)
	return result
}

var eventMgr = event.NewEventEmitter()

func RegisterWSEvent(cmd string, event event.EventHandler) {
	eventMgr.On(cmd, event)
}
func RemoveWSEvent(cmd string) {
	eventMgr.Off(cmd)
}
